import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/components/layout/Layout'
import NoLayout from '@/components/layout/noLayout.vue'
import PositionList from '@/components/recruitment/position-list'

// 导入审批组件
import RecruitmentApproval from '@/components/recruitment/approval'
import EntryApproval from '@/components/recruitment/entry-approval.vue'
import AddPosition from '@/components/recruitment/add-position.vue'
import ResumeSubmit from '@/components/recruitment/resume-submit.vue'
import EntryApprovalTask from '@/components/entry/approval.vue'
import LeaveDetail from '@/components/employee-workspace/leave-detail.vue'
import ResignationDetail from '@/components/employee-workspace/resignation-detail.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/components/login')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/components/register')
  },
  {
    path: '/home',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('@/components/home'),
        meta: { title: '首页' }
      }
    ]
  },
  {
    path: '/approval',
    component: Layout,
    meta: { title: '审批管理' },
    children: [
      {
        path: 'list',
        name: 'ApprovalList',
        component: () => import('@/components/approval/list'),
        meta: { title: '审批列表' }
      },
      {
        path: 'completed',
        name: 'CompletedApproval',
        component: () => import('@/components/approval/completed'),
        meta: { title: '已完成' }
      }
    ]
  },
  {
    path: '/personnel',
    component: Layout,
    meta: { title: '人员管理' },
    children: [
      {
        path: 'employees',
        name: 'Employees',
        component: () => import('@/components/personnel/employees'),
        meta: { title: '员工管理' }
      },
      {
        path: 'roles',
        name: 'Roles',
        component: () => import('@/components/personnel/roles'),
        meta: { title: '角色权限' }
      }
    ]
  },
  {
    path: '/recruitment',
    component: Layout,
    redirect: '/recruitment/positions',
    name: 'Recruitment',
    meta: { title: '招聘管理', icon: 'el-icon-user' },
    children: [
      {
        path: 'demands',
        name: 'RecruitmentDemands',
        component: () => import('@/components/recruitment/demands'),
        meta: { title: '需求管理' }
      },
      {
        path: 'add-demand',
        name: 'AddDemand',
        component: () => import('@/components/recruitment/add-demand'),
        meta: { title: '招聘需求', noCache: true }
      },
      {
        path: 'resumes',
        name: 'RecruitmentResumes',
        component: () => import('@/components/recruitment/resumes'),
        meta: { title: '简历管理' }
      },
      {
        path: 'manage',
        name: 'RecruitmentManage',
        component: () => import('@/components/recruitment/manage'),
        meta: { title: '招聘管理' }
      },
      {
        path: 'approval',
        name: 'RecruitmentApproval',
        component: RecruitmentApproval,
        meta: {
          title: '招聘审批'
        }
      },
      {
        path: 'process-detail',
        name: 'ProcessDetail',
        component: () => import('@/components/recruitment/process-detail'),
        meta: { 
          title: '流程详情'
        }
      },
      {
        path: 'entry-approval',
        name: 'EntryApproval',
        component: EntryApproval,
        meta: {
          title: '入职审批',
          icon: 'el-icon-user-check'
        }
      },
      {
        path: 'positions',
        name: 'PositionList',
        component: PositionList,
        meta: { title: '职位列表', icon: 'el-icon-document' }
      },
      {
        path: 'add-position',
        name: 'AddPosition',
        component: AddPosition,
        meta: { title: '新增职位', icon: 'el-icon-plus' }
      },
      {
        path: 'resume-submit',
        name: 'ResumeSubmit',
        component: ResumeSubmit,
        meta: { title: '简历投递', icon: 'el-icon-upload' }
      },
      {
        path: 'interview-approval',
        name: 'InterviewApproval',
        component: () => import('@/components/recruitment/interview-approval.vue'),
        meta: {
          title: '面试审批'
        }
      },
      {
        path: 'interview-process',
        name: 'InterviewProcess',
        component: () => import('@/components/recruitment/interview-process.vue'),
        meta: {
          title: '面试流程查看'
        }
      },
      {
        path: 'interview-start',
        name: 'InterviewStart',
        component: () => import('@/components/recruitment/interview-start.vue'),
        meta: {
          title: '面试流程开启'
        }
      }
    ]
  },
  {
    path: '/organization',
    component: Layout,
    meta: { title: '组织架构' },
    children: [
      {
        path: 'departments',
        name: 'OrgDepartments',
        component: () => import('@/components/organization/departments'),
        meta: { title: '部门管理' }
      },
      {
        path: 'positions',
        name: 'OrgPositions',
        component: () => import('@/components/organization/positions'),
        meta: { title: '岗位管理' }
      }
    ]
  },
  {
    path: '/hr-workspace',
    component: Layout,
    meta: { 
      title: '人事工作台',
      icon: 'el-icon-s-platform'
    },
    children: [
      {
        path: 'dashboard',
        name: 'HRDashboard',
        component: () => import('@/components/hr-workspace/Dashboard'),
        meta: { 
          title: '工作台',
          icon: 'el-icon-data-board'
        }
      }
    ]
  },
  // 员工工作台路由
  {
    path: '/employee',
    component: Layout,
    redirect: '/employee/dashboard',
    name: 'Employee',
    meta: { title: '员工工作台', icon: 'el-icon-user' },
    children: [
      {
        path: 'dashboard',
        component: () => import('@/components/employee-workspace/Dashboard'),
        name: 'EmployeeDashboard',
        meta: { title: '工作台' }
      },
      {
        path: 'leave',
        component: () => import('@/components/employee-workspace/leave'),
        name: 'LeaveApplication',
        meta: { title: '请假申请' }
      },
      {
        path: 'leave-detail',
        component: () => import('@/components/employee-workspace/leave-detail'),
        name: 'LeaveDetail',
        meta: {
          title: '请假详情'
        }
      },
      {
        path: 'resignation',
        name: 'Resignation',
        component: () => import('@/components/employee-workspace/resignation.vue'),
        meta: {
          title: '离职申请'
        }
      },
      {
        path: 'resignation-detail',
        name: 'ResignationDetail',
        component: ResignationDetail,
        meta: {
          title: '离职详情'
        }
      },
      {
        path: 'probation',
        name: 'Probation',
        component: () => import('@/components/employee-workspace/probation.vue'),
        meta: {
          title: '转正申请'
        }
      },
      {
        path: 'probation-detail',
        name: 'ProbationDetail',
        component: () => import('@/components/employee-workspace/probation-detail.vue'),
        meta: {
          title: '转正详情'
        }
      }
    ]
  },
  // 绩效管理路由
  {
    path: '/performance',
    component: Layout,
    meta: { 
      title: '绩效管理',
      icon: 'el-icon-s-data'
    },
    children: [
      {
        path: 'indicators',
        name: 'PerformanceIndicators',
        component: () => import('@/components/performance/indicators'),
        meta: { 
          title: '指标库',
          icon: 'el-icon-collection'
        }
      },
      {
        path: 'templates',
        name: 'PerformanceTemplates',
        component: () => import('@/components/performance/templates'),
        meta: { 
          title: '考核模板',
          icon: 'el-icon-s-order'
        }
      },
      {
        path: 'assessment-plan',
        name: 'AssessmentPlan',
        component: () => import('@/components/performance/assessment-plan'),
        meta: { 
          title: '考核计划',
          icon: 'el-icon-s-claim'
        }
      },
      {
        path: 'results',
        name: 'PerformanceResults',
        component: () => import('@/components/performance/results'),
        meta: { 
          title: '考核结果',
          icon: 'el-icon-s-marketing'
        }
      },
      {
        path: 'approval',
        name: 'PerformanceApproval',
        component: () => import('@/components/performance/approval'),
        meta: { 
          title: '绩效审批',
          activeMenu: '/approval/list'
        }
      },
      {
        path: 'process-detail',
        name: 'PerformanceProcessDetail',
        component: () => import('@/components/performance/process-detail'),
        meta: { 
          title: '绩效流程详情',
          activeMenu: '/approval/list'
        }
      }
    ]
  },
  // 考勤管理路由
  {
    path: '/attendance',
    component: Layout,
    meta: { 
      title: '考勤管理',
      icon: 'el-icon-date'
    },
    children: [
      {
        path: 'check-in',
        name: 'CheckIn',
        component: () => import('@/components/attendance/check-in.vue'),
        meta: { 
          title: '打卡',
          icon: 'el-icon-position'
        }
      },
      {
        path: 'view',
        name: 'AttendanceView',
        component: () => import('@/components/attendance/attendance-view.vue'),
        meta: { title: '考勤查看', icon: 'el-icon-view' }
      }
    ]
  },
  // 入职管理路由
  {
    path: '/entry',
    component: Layout,
    name: 'Entry',
    meta: { title: '入职管理', icon: 'el-icon-user' },
    children: [
      {
        path: 'approval',
        name: 'EntryApprovalTask',
        component: EntryApprovalTask,
        meta: { 
          title: '入职审批',
          activeMenu: '/approval/list'
        }
      },
      {
        path: 'process-detail',
        name: 'EntryProcessDetail',
        component: () => import('@/components/entry/process-detail'),
        meta: { title: '入职流程详情', activeMenu: '/approval/list' },
        hidden: true
      }
    ]
  },
  //未登录用户路由
  {
    path: '/no-layout',
    component: NoLayout,
    children: [
      {
        path: 'position-list',
        name: 'PublicPositionList',
        component: () => import('@/components/recruitment/position-list.vue')
      },
      {
        path: 'resume-submit',
        name: 'PublicResumeSubmit',
        component: () => import('@/components/recruitment/resume-submit.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由拦截器
router.beforeEach((to, from, next) => {
  // 获取token
  const token = window.sessionStorage.getItem('token')
  
  // 白名单路由，不需要登录就可以访问
  const whiteList = ['/login', '/register', '/no-layout']
  
  if (!token) {
    // 如果没有token，且访问的不是白名单页面，则重定向到登录页
    if (whiteList.includes(to.path) || to.path.startsWith('/no-layout/')) {
      next()
    } else {
      next('/login')
    }
  } else {
    // 如果有token，但是没有权限信息，先获取权限信息
    const authority = window.sessionStorage.getItem('authority')
    
    if (!authority) {
      // 获取用户信息
      Vue.prototype.$axios.get('/security/sysUsr/accountUser').then(res => {
        if (res.result == 200) {
          const userData = res.data
          // 提取权限信息
          const userAuthority = userData.authorities && userData.authorities.length > 0 
            ? userData.authorities[0].authority 
            : null
            
          // 保存用户信息到sessionStorage
          window.sessionStorage.setItem('userInfo', JSON.stringify(userData))
          window.sessionStorage.setItem('authority', userAuthority)
          
          // 检查路由权限
          checkRoutePermission(to, next, userAuthority)
        } else {
          next('/login')
        }
      }).catch(() => {
        next('/login')
      })
    } else {
      // 检查路由权限
      checkRoutePermission(to, next, authority)
    }
  }
})

// 检查路由权限
function checkRoutePermission(to, next, authority) {
  // 根路径或首页，所有人都可以访问
  if (to.path === '/' || to.path === '/home') {
    next()
    return
  }
  
  // 管理员可以访问所有页面
  if (authority === '0') {
    next()
    return
  }
  
  // 领导可以访问的页面
  if (authority === '1') {
    // 领导可以访问首页、人事工作台、招聘管理、绩效管理
    if (to.path.startsWith('/hr-workspace') || to.path.startsWith('/recruitment') || to.path.startsWith('/performance')) {
      next()
    } else {
      next('/home')
    }
    return
  }
  
  // 员工只能访问首页
  if (authority === '2') {
    // 允许员工访问首页和员工工作台
    if (to.path === '/home' || to.path.startsWith('/employee')) {
      next()
    } else {
      next('/employee/dashboard') // 默认导向员工工作台
    }
    return
  }
  
  // 默认到首页
  next('/home')
}

export default router
